package com.ffzx.parentweb.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.config.spring.ReferenceBean;
import com.alibaba.dubbo.remoting.ExecutionException;
import com.alibaba.dubbo.rpc.service.GenericService;
import com.ffzx.commerce.framework.controller.BaseController;
import com.ffzx.commerce.framework.dto.ResultDto;
import com.ffzx.commerce.framework.utils.DateUtil;
import com.ffzx.commerce.framework.utils.FTPUtil;
import com.ffzx.commerce.framework.utils.ImageAttribute;
import com.ffzx.commerce.framework.utils.ImageUtil;
import com.ffzx.commerce.framework.utils.SingletonDubboApplication;
import com.ffzx.commerce.framework.utils.StringUtil;
import com.ffzx.commerce.framework.utils.UUIDGenerator;


/**
 * 图片上传  公共Controller
 * 	
 * @author liujunjun
 * @date 2016年5月10日 下午3:19:37
 * @version 1.0
 */
@Controller
@RequestMapping("/uploadImage")
public class UploadImageController extends BaseController {

	private final static Logger logger = LoggerFactory.getLogger(UploadImageController.class);
	
	@Autowired
	private MessageChannel ftpUploadChannel;	
	
	/**
	 *  上传图片
	 * @param file   				图片文件
	 * @param ordingName			图片名称
	 * @param type					上传图片的类型====在基础数据系统-辅助属性中设置-上传图片类型中添加（必填）	
	 * @param path					追加自定义url（选填) 
	 * @param response
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	@RequestMapping(value="upload",method=RequestMethod.POST)
	public void upload(@RequestParam(value="image")MultipartFile file,
			@RequestParam(value="fileName",required=false)String ordingName,
			@RequestParam(value="type",required=false)String type, String path,
			HttpServletResponse response) throws IOException, InterruptedException, ExecutionException{
		Map<String, Object> output = new HashMap<String, Object>();

		try {
			final byte[] bytes = file.getBytes();
			final String fileName = file.getOriginalFilename();
			final String suffix = fileName.substring(fileName.lastIndexOf("."));
			
			List<ImageAttribute> list = new ArrayList<ImageAttribute>();	

			String savePath = DateUtil.formatMonthDate(new Date());
			/*
			 * 通过类型设置需要保存的图片
			 */
			if(StringUtil.isNotNull(type)){
				String imgType = getDictByType("sys_img_type",type);
				if(StringUtil.isNotNull(imgType) && !imgType.equals("-1")){
					//width 或  height 属性为空则原图保存
					ImageAttribute imgattr = new ImageAttribute(null,null,true);
					list.add(imgattr);
					String[] sizeList = imgType.split(";") ;
					String[] itemSize;
					for (String string : sizeList) {
						itemSize = string.split("X");
						imgattr = new ImageAttribute(Integer.parseInt(itemSize[0].trim()),Integer.parseInt(itemSize[1].trim()),true);
						list.add(imgattr);
					}
				}else{
					//width 或  height 属性为空则原图保存
					ImageAttribute imgattr = new ImageAttribute(null,null,false);
					list.add(imgattr);
				}
				savePath = type + "/" +DateUtil.formatMonthDate(new Date());
			}		
			
			if(StringUtil.isNotNull(path)){
				savePath = savePath + "/" +path;
				
			}
			savePath="new_2016/"+savePath;
			//保存图片
			String imgUrl = compressSave(bytes,savePath,suffix,list);
			
			//返回图片路径
			String imgPath = "/" + savePath + "/" + imgUrl + "_size"+ suffix;
			if(StringUtils.isBlank(imgUrl)){
				output.put("status", "-1");
				output.put("infoStr", "上传文件失败");
				output.put("path", imgPath);
				output.put("imgPath", System.getProperty("image.web.server") + imgPath);
			}else{
				output.put("status", "0");
				output.put("infoStr", "上传文件成功");
				output.put("path", imgPath);
				output.put("imgPath", System.getProperty("image.web.server") + imgPath);
			}
			
		} catch (Exception e) {
			output.put("status", "1");
			output.put("infoStr", "上传文件失败");
			logger.error("UploadImageController-upload=》图片上传-ServiceException", e);
		}
		this.responseWrite(response, this.getJsonByObject(output));
	}
	
	/**
	 * 按图片属性列表参数压缩不同尺寸的图片,返回随机生成的图片名,图片保存名为 XXX_100X75.png
	 * @param bytes
	 * @param path  图片目录
	 * @param suffix 图片后缀
	 * @param list  图片属性列表
	 * @return
	 */
	public String compressSave(byte[] bytes,String path, String suffix,List<ImageAttribute> list){
		String fileId = UUIDGenerator.getUUID();
		Boolean result = false;
		for(ImageAttribute imgattr : list) {
			
			//压缩图片
			byte[] compressedImage = ImageUtil.resize(bytes, imgattr.getWidth(), imgattr.getHeight(), imgattr.isEqualRatio());
			
			//设置图片后缀
			String nameSuffix = 
				imgattr.isNoShowSuffix()?"":((null==imgattr.getWidth()||null==imgattr.getHeight())?"_origin":("_"+imgattr.getWidth()+"X"+imgattr.getHeight()));
			String tmpname = fileId+nameSuffix+suffix;
						
			//设置图片路径
			String  targetFilePath = path;
				
			try {
				//上传图片到ftp服务器
				result = FTPUtil.ftpUpload(ftpUploadChannel, compressedImage, tmpname, targetFilePath);
				if(!result){
					break;
				}
				
			} catch (Exception e) {
				logger.error("UploadImageController-compressSave=》图片上传-compressSave-ServiceException", e);
				result=false;
				break;
			}
		}
		if(result){
			return fileId;
		}
		return null;
				
	}
	
	/**
	 * 初始化图片类型
	 * 
	 * @param session
	 */
	public String getDictByType(String type,String label) {
		try {
			Map<?, ?> genericResult = (Map<?, ?>) dictApiService.$invoke("getDictByParams", new String[] { "java.lang.String", "java.lang.String" }, new Object[] { type , label});
			ResultDto resultDto = new ResultDto();
			resultDto.setCode((String)genericResult.get("code"));
			resultDto.setMessage((String)genericResult.get("message"));

			if (resultDto != null && resultDto.getCode().equals(ResultDto.OK_CODE)){
				return (String)genericResult.get("data");
			}
		} catch (Exception e) {
			logger.error("UploadImageController-getDictByType-Exception=》-获取图片类型-Exception", e);
		}
		return null;
	}
	
	private GenericService dictApiService;	
	{
		ReferenceBean<GenericService> referenceConfig = new ReferenceBean<GenericService>();
		referenceConfig.setInterface("com.ffzx.basedata.api.service.DictApiService");
		referenceConfig.setGeneric(Boolean.TRUE);
		referenceConfig.setVersion("1.0");
		referenceConfig.setId("dictApiService");
		SingletonDubboApplication.getInstance().destroyBean(referenceConfig.getId());
		SingletonDubboApplication.getInstance().addReferenceBean(referenceConfig.getId(), referenceConfig);
		dictApiService = (GenericService) SingletonDubboApplication.getInstance().getReferenceObject(referenceConfig.getId());
	}
	
}
